package com.hospicpc.demos.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hospicpc.demos.commom.Result;
import com.hospicpc.demos.entity.dto.LoginRes;
import com.hospicpc.demos.entity.User;
import com.hospicpc.demos.entity.UserInfo;
import com.hospicpc.demos.entity.dto.UserInfoDto;
import com.hospicpc.demos.service.Impl.UserInfoServiceImpl;
import com.hospicpc.demos.service.Impl.UserServiceImpl;
import com.hospicpc.demos.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.hospicpc.demos.commom.UserDefaultInfo.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fengtianhao
 * @since 2023-11-19
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private UserInfoServiceImpl userInfoService;

    /**
     * @author fengtianhao
     */
    public static String getToken(String val,Long id){
        Map<String, Object> map = new HashMap<>();
        map.put("openid", val);
        map.put("id",id);
        final String token = JwtUtil.getJWT(map, 60 * 60 * 1000 * 24 * 15L);
        return token;
    }

    /**
     * 通过微信openId登录
     * @param
     * @param httpSession
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/login/openid")
    @Transactional(rollbackFor = Exception.class)
    public Result loginByopenId(@RequestBody Map<String,String> m,HttpSession httpSession,HttpServletRequest httpServletRequest) {
        //1.获取code
        final String code = m.get("code");

        //2.根据code发送请求获取openid
        final String openid;
        String str = HttpUtils.getOpenidByCode(code);
        //3.将str转化为map
        Map<String, Object> stringObjectMap = FormatConversionUtils.stringToMap(str);

        //4.判断stringObjectMap的合法性
        if(stringObjectMap.containsKey("errmsg")) {
            return Result.error(stringObjectMap.get("errmsg").toString());
        }

        //5.给openid赋值
        openid = stringObjectMap.get("openid").toString();

        //6.通过openId查找数据库中是否已存在信息
        final User user = userService.getUserByOpenid(openid);

        //7.不存在,创建用户并存入数据库
        if (null == user) {
            //7.1创建user表信息
            User newUser = new User();
            newUser.setOpenid(openid);
            //默认权限2，普通用户
            newUser.setStatus(2);
            try {
                userService.save(newUser);
            }catch (Exception e) {
                e.printStackTrace();
                return Result.error("服务异常");
            }

            //7.2获取刚user表创建值的id
            User u = userService.getOne(new QueryWrapper<User>().eq("openid", openid));
            System.out.println(u);
            Long id = u.getId();

            //7.3创建userInfo表信息
            UserInfo userInfo = new UserInfo();
            //给新用户创建一个9位数编号
            RandomNumber randomNumber = new RandomNumber(1L);//设置机器id
            Long number = (randomNumber.generateUniqueId()% 1000000000);
            userInfo.setNumber(number.toString());
            userInfo.setUserId(id);
            userInfo.setDescription(DEFAULT_DESCRIPTION);
            userInfo.setAvatarUrl(DEFAULT_AVATAR_URL);
            userInfo.setNickName(DEFAULT_NICKNAME+number);
            try {
                userInfoService.save(userInfo);
            }catch (Exception e) {
                e.printStackTrace();
                return Result.error("服务异常");
            }

            //7.4创建成功，返回token与用户信息
            UserInfo res = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_id", id));
            //7.5使用hutool工具完成实体类与dto类的转化
            UserInfoDto userInfoDto = new UserInfoDto();
            BeanUtil.copyProperties(res,userInfoDto);
            userInfoDto.setRole(res.getRole());
            System.out.println(res);
            return Result.success(new LoginRes(getToken(openid,id),userInfoDto));
        }

        //8.账号异常
        if(user.getStatus().equals(1)){
            return Result.error("账号异常");
        }

        //9.账号存在，返回token与用户信息
        UserInfo res = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_id", user.getId()));
        //使用hutool工具完成实体类与dto类的转化
        UserInfoDto userInfoDto = new UserInfoDto();
        BeanUtil.copyProperties(res,userInfoDto);
        userInfoDto.setRole(user.getRole());
        return Result.success(new LoginRes(getToken(openid,user.getId()),userInfoDto));
    }


    // /**
    //  * 通过手机号登录
    //  * @param map
    //  * @param httpSession
    //  * @param httpServletRequest
    //  * @return
    //  */
    // @PostMapping("/login/phone")
    // public Result loginByPhone(@RequestBody Map<String,String> map, HttpSession httpSession, HttpServletRequest httpServletRequest){
    //     //获取sessionKey，encryptedData，iv
    //     final String session_key = map.get("session_key");
    //     final String encryptedData = map.get("encryptedData");
    //     final String iv = map.get("iv");
    //     System.out.println(session_key);
    //     System.out.println(encryptedData);
    //     System.out.println(iv);
    //     //获取手机号
    //     String phone = "15551233167";
    //     try {
    //         String s = AESUtils.decryptForWeChatApplet(encryptedData, session_key, iv);
    //         System.out.println(s);
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    //     // System.out.println(decrypt);
    //     //通过手机号查找数据库中是否已存在信息
    //     final User user = userService.getUserByPhone(phone);
    //     System.out.println(user);
    //     //不存在,创建对象存入数据库
    //     if (null == user) {
    //         User newUser = new User();
    //         newUser.setPhone(phone);
    //         userService.save(newUser);
    //         //获取刚创建值的id
    //         User u = userService.getOne(new QueryWrapper<User>().eq("phone", phone));
    //         Long id = u.getId();
    //         return Result.success(getToken(phone,id));
    //     }
    //     if(user.getStatus().equals(1)){
    //         return Result.error("账号异常");
    //     }
    //     //已存在，直接返回token
    //     return Result.success(getToken(phone,user.getId()));
    // }

}
